$(function () {
	var win = $(window),
		doc = $(document),
		hb = $("html, body"),
		s = $("#s"),
		rocket = $("#rocket"),
		ie6 = $("html").hasClass("lt-ie7"),
		ie7 = $("html").hasClass("lt-ie8");

	//移动版切换搜索框
	$("#m-btns .search").click(function () {
		$("body").toggleClass("m-search");
		s.focus();
	});

	//IE7下搜索框处理
	if (ie7) {
		s.focus(function () {
			s.addClass("focus");
		}).blur(function () {
			s.removeClass("focus");
		});
	};

	//返回顶部
	if (!(ie6 || window.matchMedia && window.matchMedia("(max-width: 540px)").matches)) {
		var sidebar = $("#sidebar"),
			sidebarPoint = sidebar.height() + sidebar.offset().top,
			newsletter = $("#newsletter");
		win.scroll(function () {
			win.scrollTop() > Math.max(400, win.height()) ? rocket.addClass("show") : rocket.removeClass("show");
			win.scrollTop() > sidebarPoint ? newsletter.addClass("sticky") : newsletter.removeClass("sticky");
		}).resize(function(){
			newsletter.css("left", sidebar.offset().left);
		}).resize();
	};
	rocket.click(function () {
		rocket.addClass("launch");
		hb.animate({
			scrollTop: 0
		}, 600, function () {
			rocket.removeClass("show launch");
		});
		return false;
	});

	//侧边栏幻灯片
	if (typeof (slideList) != "undefined" && slideList.length) {
		var slides = $("#slides"),
			slideLength = slideList.length,
			slideIndex = 0,
			slideTimer;
		slides.html('<a href="' + slideList[0].link + '" title="' + slideList[0].title + '"><img src="' + slideList[0].image + '" alt="' + slideList[0].title + '"></a>');
		
		function slideGo(n) {
			var orig = $("a", slides);
			slideIndex = !isNaN(n) ? n : slideIndex < slideLength - 1 ? slideIndex + 1 : 0;
			orig.clone().addClass("temp").appendTo(slides).fadeOut(function () {
				$(this).remove()
			});
			orig.attr("href", slideList[slideIndex].link).attr("title", slideList[slideIndex].title).html('<img src="' + slideList[slideIndex].image + '" alt="' + slideList[slideIndex].title + '">');
		};

		if(slideLength > 2) {
			var prev = $("<span class='prev'>&lsaquo;</span>"),
				next = $("<span class='next'>&rsaquo;</span>");
			prev.click(function(){
				slideGo(slideIndex == 0 ? slideLength - 1 : slideIndex - 1);
			});
			next.click(function(){
				slideGo();
			});
			slides.append(prev).append(next).hover(function(){
				clearInterval(slideTimer);
			}, function(){
				slideTimer = setInterval(slideGo, 7e3);
			});

			slideTimer = setInterval(slideGo, 7e3);
		};
	};

	//AJAX加载文章列表
	var main = $("#main"),
		loadingPosts = 0;

	main.on("click", ".loadmore", function (e, needScroll) {
		if (loadingPosts) return false;
		
		var a = $(this).attr("title", "正在加载…").addClass("loading");

		loadingPosts = 1;

		$.get( a.attr("href"), function(data) {
			a.parent().remove();
			
			var dHtml = $(data),
				dPosts = dHtml.find(".hentry").addClass("fadein");
			
			main.append(dPosts).append(dHtml.find(".navigation"));

			if(needScroll) scrollToPost(dPosts.eq(0));

			loadingPosts = 0;
		});
		return false;
	});

	//AJAX加载评论列表
	var comments = $("#comments");
	comments.on("click", ".loadmore", function () {
		var a = $(this);

		if (a.hasClass("loading")) return false;
		a.attr("title", "正在加载…").addClass("loading");

		$.get( a.attr("href"), function(data) {
			a.remove();
			comments.append($(data).find(".commentlist").addClass("fadein")).append($(data).find(".loadmore"));
		});
		return false;
	});

	//评论框相关
	var comment = $("#comment"),
		commentSettings = $("#comment-settings"),
		commentSettingsToggle = $(".comment-settings-toggle"),
		commentSettingsSpan = $("span", commentSettingsToggle),
		authorInput = $("#author"),
		submit = $("#submit");

	commentSettingsToggle.click(function () {
		if (!commentSettings.hasClass("show")) {
			commentSettings.addClass("show");
			$(this).removeClass("required");
			authorInput.focus();
			setTimeout(function () {
				doc.on("click.comment", function (e) {
					if (!(commentSettings.find(e.target).length || e.target == commentSettings[0])) {
						commentSettings.removeClass("show");
						doc.off("click.comment");
					};
				});
			}, 100);
		};
	});
	authorInput.on("change input", function () {
		commentSettingsSpan.text($(this).val());
	});

	comment.keydown(function (e) {
		if (e.ctrlKey && e.keyCode == 13) {
			submit.click();
		} else if (e.keyCode == 9) {
			commentSettingsToggle.click();
			return false;
		};
	});

	$(".comments-link").click(function () {
		comment.focus();
	});

	$("#respond input, #respond textarea").on("invalid", function () {
		$(this).one("input change", function () {
			$(this).parent().removeClass("invalid");
		}).parent().addClass("invalid");
		$(this).attr("id") != "comment" && commentSettingsToggle.click();
		submit.val("发表评论").prop("disabled", false);
	});

	$("#commentform").submit(function () {
		submit.val("发表中…").prop("disabled", true);
	});

	var email = $("#email");
	if (email.length && !! window.HTMLDataListElement) {
		var emaillist = $("#emaillist"),
			emaillistorightml = emaillist.html();
		emaillist.empty();
		email.on("input", function () {
			var val = $(this).val();
			val == "" ? emaillist.empty() : val.indexOf("@") == -1 && emaillist.html(emaillistorightml.replace(/\*/g, val));
		});
	};

	//快捷键导航
	var currentPost;
	$(document).keypress(function(e) {
		var tagName = e.target.tagName;
		if(tagName == "TEXTAREA" || tagName == "INPUT") return;

		switch(e.which) {
			case 106://j
				var prevPostLink = $(".previous-post a")[0];
				if(prevPostLink) {
					location.href = prevPostLink.href;
				} else {
					if(loadingPosts) return;
					if(!currentPost) {
						scrollToPost($(".hentry").eq(1));
					} else {
						var olderPost = currentPost.next();
						if(olderPost.hasClass("ga")) olderPost = olderPost.next();
						if(olderPost.hasClass("hentry")) {
							scrollToPost(olderPost);
						} else if($(".loadmore").length) {
							$(".loadmore").trigger("click", 1);
							hb.animate({scrollTop: doc.height()}, 500);
						};
					};
				};
				e.preventDefault();
				break;
			case 107://k
				var nextPostLink = $(".next-post a")[0];
				if(nextPostLink) {
					location.href = nextPostLink.href;
				} else {
					if(loadingPosts) return;
					if(!currentPost) {
						scrollToPost($(".hentry").eq(1));
					} else {
						var newerPost = currentPost.prev();
						if(newerPost.hasClass("ga")) newerPost = newerPost.prev();
						if(newerPost.hasClass("hentry")) {
							scrollToPost(newerPost);
						};
					};
				};
				e.preventDefault();
				break;
			case 114://r
				$("#comment").focus();
				e.preventDefault();
				break;
			case 47:///
				$("#s").focus();
				e.preventDefault();
				break;
		};
	});

	function scrollToPost(post) {
		if(post) {
			currentPost = post;
			hb.stop().animate({scrollTop: currentPost.offset().top - 85}, 500);
		};
	};

	$(".wumii-footer").remove();

	$(".widget-title span").each(function(){
		var span = $(this);
		span.attr("title", span.text());
	});
});


function insertSmiley(code) {
	code = " " + code + " ";
	var textarea = document.getElementById("comment");
	if(textarea) {
		if (document.selection) {
			textarea.focus();
			rng = document.selection.createRange();
			rng.text = code;
			textarea.focus();
		} else if (!isNaN(textarea.selectionStart)) {
			var selStart = textarea.selectionStart,
				selEnd = textarea.selectionEnd;
			textarea.value = textarea.value.substring(0, selStart) + code + textarea.value.substring(selEnd);
			textarea.focus();
			textarea.selectionStart = textarea.selectionEnd = selStart + code.length;
		} else {
			textarea.value += code;
			textarea.focus();
		};
	};
};

function share2(w) {
	var url = encodeURIComponent(location.href),
		pic = encodeURIComponent($("article img").attr("src")),
		title = document.title,
		summary = $(".entry-content").text().replace(/\n|\t|\r/g, '').substring(0, 140 - 2 - title.length) + "…",
		text = encodeURIComponent("【" + title + "】" + summary),
		title = encodeURIComponent(title),
		summary = encodeURIComponent(summary),
		sharelink = "";

	switch (w) {
		default:
	case "weibo":
		sharelink = "http://service.weibo.com/share/share.php?url=" + url + "&title=" + text + "&pic=" + pic + "&appkey=1948528363&ralateUid=1616215457";
		break;
	case "qzone":
		sharelink = "http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=" + url + "&summary=" + summary + "&title=" + title + "&pics=" + pic + "&site=" + encodeURIComponent("小影志");
		break;
	case "tqq":
		sharelink = "http://share.v.t.qq.com/index.php?c=share&a=index&url=" + url + "&pic=" + pic + "&title=" + text + "&appkey=801371529&assname=cople7";
		break;
	case "renren":
		sharelink = "http://widget.renren.com/dialog/share?resourceUrl=" + url + "&pic=" + pic + "&title=" + title + "&description=" + summary;
		break;
	case "qq":
		sharelink = "http://connect.qq.com/widget/shareqq/index.html?url=" + url + "&summary=" + summary + "&title=" + title + "&pics=" + pic + "&site=" + encodeURIComponent("小影志");
		break;
	case "douban":
		sharelink = "http://www.douban.com/recommend/?url=" + url + "&title=" + title + "&sel=" + summary + "&v=1";
		break;
	};
	window.open(sharelink, "", "width=700,height=680,left=" + (window.screen.availWidth - 700) / 2 + ",top=" + (window.screen.availHeight - 680) / 2 + ",toolbar=no,menubar=no,status=no,location=yes,resizable=yes,scrollbars=1");
};